package ar.com.tallerdos.smartdinner.activity;

import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import ar.com.tallerdos.smartdinner.business.RubroBusiness;
import ar.com.tallerdos.smartdinner.model.Rubro;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class RubrosLista extends ListActivity {
    public final static String RUBRO_SELECCIONADO = "ar.com.tallerdos.smartdinner.activity.RubrosLista.RUBRO_SELECCIONADO";
    List<Rubro> rubros;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	rubros = RubroBusiness.findAll();

	this.setListAdapter(new ArrayAdapter<Rubro>(this,
		android.R.layout.simple_list_item_1, rubros));
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
	Intent intent = new Intent(this, SubrubrosLista.class);

	Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
		.create();

	String subrubrosJson = gson.toJson(rubros.get(position).getSubrubros());

	intent.putExtra(RUBRO_SELECCIONADO, subrubrosJson);
	startActivityForResult(intent, 1);
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	if (requestCode == 1) {

	    if (resultCode == RESULT_OK) {
		Intent returnIntent = new Intent();
		returnIntent.putExtra("result", data.getIntExtra("result", 0));
		setResult(RESULT_OK, returnIntent);
		finish();
	    }
	    if (resultCode == RESULT_CANCELED) {
		// Write your code if there's no result
	    }
	}
	finish();
    }
}
